﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SVNUG.Tracker.Models;

namespace SVNUG.Tracker.Controllers
{
    [HandleError]
    public class DashboardController : Controller
    {
        TrackerEntities trackerDB = new TrackerEntities();

        //
        // GET: /Dashboard/

        public ActionResult Index()
        {
            var myTasks = from myTask in trackerDB.Tasks
                          select myTask;

            return View(myTasks);
        }

        //
        // GET: /Dashboard/Details/5

        public ActionResult Details(int id)
        {
            var task = trackerDB.Tasks.Single(a => a.TaskId == id);

            return View(task);
        }

        //
        // GET: /Dashboard/Create

        public ActionResult Create()
        {
            var task = new Task();

            return View(task);
        }

        //
        // POST: /Dashboard/Create

        [HttpPost]
        public ActionResult Create(Task task)
        {
            if (ModelState.IsValid)
            {
                // Save task
                trackerDB.AddToTasks(task);
                trackerDB.SaveChanges();

                return RedirectToAction("Index");
            }

            // Invalid – redisplay with errors
            return View(task);
        }

        //
        // GET: /Dashboard/Edit/5

        public ActionResult Edit(int id)
        {
            var task = trackerDB.Tasks.Single(a => a.TaskId == id);

            return View(task);
        }

        //
        // POST: /Dashboard/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection values)
        {
            var task = trackerDB.Tasks.Single(t => t.TaskId == id);

            try
            {
                if (ModelState.IsValid)
                {
                    // Save task
                    UpdateModel(task);
                    trackerDB.SaveChanges();

                    return RedirectToAction("Index");
                }

                // Invalid – redisplay with errors
                return View(task);
            }
            catch
            {
                //Error occurred – so redisplay the form
                return View(task);
            }
        }

        //
        // GET: /Dashboard/Delete/5

        public ActionResult Delete(int id)
        {
            var task = trackerDB.Tasks.Single(a => a.TaskId == id);

            return View(task);
        }

        //
        // POST: /Dashboard/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, string confirmButton)
        {
            var task = trackerDB.Tasks.Single(a => a.TaskId == id);

            trackerDB.DeleteObject(task);
            trackerDB.SaveChanges();

            return View("Deleted");
        }
    }
}